package com.dhcc.dao.impl;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.List;

import org.springframework.stereotype.Repository;

import com.dhcc.dao.TrainPlanDao;
import com.dhcc.dto.TrainTeaRel;
import com.dhcc.model.TrainPlan;
import com.dhcc.utils.PageControl;
import com.dhcc.utils.Pager;

@Repository("trainPlanDao")
public class TrainPlanDaoImpl extends BaseDaoImpl<TrainPlan> implements
		TrainPlanDao {

	@Override
	public void delete(TrainPlan tp) {
		Method method = null;

		try {
			method = clazz.getDeclaredMethod("getTpId");

			TrainPlan exitT = (TrainPlan) entityManager.find(clazz,
					method.invoke(tp));

			if (exitT != null) {

				entityManager.remove(exitT);
			}

		} catch (NoSuchMethodException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void update(TrainPlan tp) {
		Method method = null;
		try {
			method = clazz.getDeclaredMethod("getTpId");
			TrainPlan existTp = (TrainPlan) entityManager.find(clazz,
					method.invoke(tp));
			if (existTp != null) {
				entityManager.merge(existTp);
			}
		} catch (NoSuchMethodException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		}
	}

	// 查询培训计划和培训老师
	@SuppressWarnings("unchecked")
	@Override
	public List<TrainTeaRel> queryTea() {
		String jpql = "SELECT t.tpId,t.trainTime,te.teaName FROM TrainPlan t,Teacher te WHERE t.teaId=te.teaId";
		System.out.println("正在查询：：" + clazz.getSimpleName());
		return entityManager.createQuery(jpql).getResultList();
	}

	@Override
	public Pager<TrainTeaRel> queryPage(PageControl pc) {
		Pager<TrainTeaRel> pager = new Pager<TrainTeaRel>();
		String jpql = "SELECT t.tpId,t.trainTime,te.teaName FROM TrainPlan t,Teacher te WHERE t.teaId=te.teaId";

		String jpql2 = "SELECT count(*) FROM TrainPlan t,Teacher te WHERE t.teaId=te.teaId";

		Long count = (Long) entityManager.createQuery(jpql2).getSingleResult();
		pc.setSumCount(count);

		int start = (pc.getCurrentIndex() - 1) * pc.getPagesize();

		@SuppressWarnings("unchecked")
		List<TrainTeaRel> list = entityManager.createQuery(jpql)
				.setFirstResult(start).setMaxResults(pc.getPagesize())
				.getResultList();
		pager.setList(list);
		// 页码控制设置
		pc = detailPage(pc);

		pager.setPageControl(pc);

		return pager;
	}
}
